﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      CIS  CompanyInfoHelper
// Created By:     Samara Jiang (samaraj@wicresoft.com)
// Created Date:   2011-2-9
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Security.Principal;
using System.Text;
using ASBCC.Database.EntityFramework;

namespace ASBCC.Business.CIS
{
    /// <summary>
    /// CIS  公司信息模块数据库访问类
    /// </summary>
    public static class CompanyInfoHelper
    {

        /// <summary>
        /// 获取添加公司信息的当前用户信息和时间
        /// </summary>
        public static void OnCompanyInfoInserting(ObjectContext dc, Company company, IPrincipal user)
        {
            var users = dc.CreateQuery<Employee>("[Employees]");
            company.CreateBy = users.First(p => p.NameEN == user.Identity.Name);
            company.LastModifyBy = company.CreateBy;
            company.CreateTime = DateTime.Now;
            company.LastModifyTime = DateTime.Now;
        }

        /// <summary>
        /// 获取修改公司信息的当前用户信息和时间
        /// </summary>
        public static void OnCompanyInfoUpdating(ObjectContext dc, Company company, IPrincipal user)
        {
            var users = dc.CreateQuery<Employee>("[Employees]");
            company.LastModifyBy = users.First(p => p.NameEN == user.Identity.Name);
            company.LastModifyTime = DateTime.Now;

        }

        /// <summary>
        /// 将一个company的激活状态设为未激活
        /// </summary>
        public static bool SetCompanyInfoDisabled(int companyID)
        {
            using (var dc = new CCEntities())
            {
                var company = dc.Companies.First(p => p.CompanyID == companyID);
                company.Customers.Load();
                bool flag = false;
                foreach (var customer in company.Customers)
                    if (customer.Disabled == false)
                    {
                        flag = true;
                        break;
                    }
                if (flag)
                    return false;
                company.Disabled = true;
                dc.SaveChanges();
                return true;
            }
        }

        /// <summary>
        /// 根据当前ID获取Name
        /// </summary>
        public static IEnumerable getName(int entityID)
        {
            using (var dc = new CCEntities())
            {
                var name = dc.Companies.FirstOrDefault(p => p.CompanyID == entityID).Name;
                return name;
            }
        }
        /// <summary>
        /// 海外 通过Company查询Country
        /// </summary>
        public static IEnumerable GetCountryWithCompanyRelation(int companyID)
        {
            using (CCEntities dc = new CCEntities())
            {
                var company = dc.Companies.FirstOrDefault(p => p.CompanyID == companyID);
                var countries = dc.Countries.Where(p => p.Disabled == false).ToArray();
                company.Countries.Load();
                var source = from p in countries
                             select new
                             {
                                 p.CountryID,
                                 p.Name,
                                 p.Description,
                                 ContainsCompany = company.Countries.Contains(p) ? "checked" : "",
                             };
                return source.ToArray();
            }
        }


        /// <summary>
        /// 国内Commercial修改Company时必须选择一个Province，且对应的Category为‘其他’
        /// </summary>
        public static void OnCompanyWithPCATUpdatingByCommercial(ObjectContext dc, Company company, string provinceID)
        {
            company.PCATs.Load();
            company.PCATs.Clear();
            OnCompanyWithPCATInsertingByCommercial(dc, company, provinceID);
        }



        /// <summary>
        /// 国内Commercial创建Company时必须选择一个Province，且对应的Category为‘其他’
        /// </summary>
        public static void OnCompanyWithPCATInsertingByCommercial(ObjectContext dc, Company company, string provinceID)
        {
            if (provinceID != "0")
            {
                var pcats = dc.CreateQuery<PCAT>("[PCATs]");
                int pid = int.Parse(provinceID);

                company.PCATs.Add(pcats.First(p =>
                    p.ProvinceID == pid &&
                    p.Category.Name == "其他"));
            }
        }


        /// <summary>
        /// 国内 Company修改PCAT
        /// </summary>
        public static void OnCompanyWithPCATUpdating(ObjectContext dc, Company company, string pcatnames)
        {
            company.PCATs.Load();
            company.PCATs.Clear();

            OnCompanyWithPCATInserting(dc, company, pcatnames);

        }

        /// <summary>
        /// 国内Admin创建Company
        /// </summary>
        public static void OnCompanyWithPCATInserting(ObjectContext dc, Company company, string provinceID)
        {
            if (provinceID != "0")
            {
                var pcats = dc.CreateQuery<PCAT>("[PCATs]");
                string[] pcat = provinceID.Split(';');
                int pid = int.Parse(pcat[0]);
                int cid = int.Parse(pcat[1]);

                company.PCATs.Add(pcats.First(p =>
                    p.ProvinceID == pid &&
                    p.CateID == cid));
            }
        }

        /// <summary>
        /// 为Company修改Country
        /// </summary>
        public static void OnCompanyWithCountryUpdating(ObjectContext dc, Company company, string countryList)
        {
            company.Countries.Load();
            company.Countries.Clear();

            OnCompanyWithCountryInserting(dc, company, countryList);

        }

        /// <summary>
        /// 海外Admin创建Company
        /// </summary>
        public static void OnCompanyWithCountryInserting(ObjectContext dc, Company company, string countryID)
        {
            if (countryID != "0")
            {
                var countries = dc.CreateQuery<Country>("[Countries]");
                int countryid = int.Parse(countryID);

                company.Countries.Add(countries.First(p =>
                    p.CountryID == countryid));
            }
        }


        /// <summary>
        /// 通过roles取Country
        /// </summary>
        public static IEnumerable GetManagedCountryList(string[] role, string roles, int companyID)
        {
            using (var dc = new CCEntities())
            {
                List<SelectType> result = new List<SelectType>();
                List<Country> countries = new List<Country>();
                foreach (var role1 in role)
                {
                    if (String.IsNullOrEmpty(role1))
                        continue;
                    int role2 = int.Parse(role1);
                    var role3 = dc.Roles.FirstOrDefault(p => p.BelongsTo == "CIO" && p.RoleID == role2);
                    if (role3 != null && role3.IsAdmin)
                    {
                        countries = dc.Countries.Where(p => p.Disabled == false).ToList<Country>();
                        break;
                    }
                }

                if (countries == null || countries.Count == 0)
                {
                    countries = dc.sp_GetCountriesbyRoleIDs(roles).ToList<Country>();
                }

                foreach (var country in countries)
                {
                    country.Companies.Load();
                    string ischeck = "";
                    if (companyID > 0 && country.Companies.Where(p => p.CompanyID == companyID).Count() > 0)
                        ischeck = "checked";
                    country.Areas.Load();
                    string areaName = "";
                    var area = country.Areas.FirstOrDefault();
                    if (area != null)
                        areaName = "(" + area.Name + ")";
                    result.Add(new SelectType
                    {
                        id = country.CountryID.ToString(),
                        name = country.Name + areaName,
                        ischecked = ischeck
                    });
                }
                return result;
            }
        }

        /// <summary>
        /// 通过roles取PCAT
        /// </summary>
        public static IEnumerable GetManagedPCATList(string[] role, string roles, int companyID)
        {
            using (var dc = new CCEntities())
            {
                List<SelectType> result = new List<SelectType>();
                List<PCAT> pcats = new List<PCAT>();

                foreach (var role1 in role)
                {
                    if (String.IsNullOrEmpty(role1))
                        continue;
                    int role2 = int.Parse(role1);
                    var role3 = dc.Roles.FirstOrDefault(p => p.BelongsTo == "CID" && p.RoleID == role2);
                    if (role3 != null && role3.IsAdmin)
                    {
                        pcats = dc.sp_GetAllPcatsbyRoleIDs(role3.RoleID.ToString()).ToList<PCAT>();
                        break;
                    }
                }
                if (pcats == null || pcats.Count == 0)
                {
                    pcats = dc.sp_GetPCATsbyRoleIDs(roles).ToList<PCAT>();
                }

                foreach (var pcat in pcats)
                {
                    pcat.ProvinceReference.Load();
                    pcat.CategoryReference.Load();
                    pcat.Companies.Load();
                    string ischeck = "";
                    if (companyID > 0 && pcat.Companies.Where(p => p.CompanyID == companyID).Count() > 0)
                        ischeck = "checked";
                    result.Add(new SelectType
                    {
                        id = pcat.ProvinceID.ToString() + ";" + pcat.CateID.ToString(),
                        name = pcat.Province.Name + pcat.Category.Name,
                        ischecked = ischeck
                    });
                }

                return result;
            }
        }

        /// <summary>
        /// 在创建Company时通过roles取PCAT
        /// </summary>
        public static IEnumerable GetManagedPCATListWhenInserting(UserRoles userRoles, string[] role, string roles)
        {
            using (var dc = new CCEntities())
            {
                List<SelectType> result = new List<SelectType>();
                List<PCAT> pcats = new List<PCAT>();

                foreach (var role1 in role)
                {
                    if (String.IsNullOrEmpty(role1))
                        continue;
                    int role2 = int.Parse(role1);
                    var role3 = dc.Roles.FirstOrDefault(p => p.BelongsTo == "CID" && p.RoleID == role2);
                    if (role3 != null && role3.IsAdmin)
                    {
                        pcats = dc.sp_GetAllPcatsbyRoleIDs(role3.RoleID.ToString()).ToList<PCAT>();
                        break;
                    }
                }
                if (pcats == null || pcats.Count == 0)
                {
                    pcats = dc.sp_GetPCATsbyRoleIDs(roles).ToList<PCAT>();
                    if (userRoles.IsDomesticCommercial)
                    {
                        int[] provinceID = new int[1000];
                        int index = 0;
                        foreach (var pcat in pcats)
                        {
                            provinceID[index] = (int)pcat.ProvinceID;
                            index++;
                        }
                        var distinctProvinceID = provinceID.Distinct();
                        List<PCAT> pcats1 = new List<PCAT>();
                        int cID = dc.Categories.FirstOrDefault(p => p.Name == "Others" && p.Disabled == false).CateID;
                        foreach (var pID in distinctProvinceID)
                        {
                            if (pID != 0 && pcats.Where(p => p.ProvinceID == pID).Count() == dc.PCATs.Where(p => p.ProvinceID == pID).Count())
                                pcats1.Add(dc.PCATs.First(p => p.ProvinceID == pID && p.CateID == cID));
                        }
                        pcats = pcats1;
                    }
                }

                foreach (var pcat in pcats)
                {
                    pcat.ProvinceReference.Load();
                    pcat.CategoryReference.Load();
                    pcat.Companies.Load();
                    string ischeck = "";
                    result.Add(new SelectType
                    {
                        id = pcat.ProvinceID.ToString() + ";" + pcat.CateID.ToString(),
                        name = pcat.Province.Name + pcat.Category.Name,
                        ischecked = ischeck
                    });
                }

                return result;
            }
        }

        public static string GetProvinceNameByCompanyID(int companyID)
        {
            using (var dc = new CCEntities())
            {
                var company = dc.Companies.First(p => p.CompanyID == companyID);
                company.PCATs.Load();
                var pcats = company.PCATs.ToArray();
                int provinceID = pcats.First().ProvinceID;
                return dc.Provinces.First(p => p.ProvinceID == provinceID).Name;
            }
        }

        /// <summary>
        /// 获取用户角色所对应的权限
        /// </summary>
        public static UserRoles GetUserRightByRoleIDs(string[] RoleIDs)
        {
            using (var dc = new CCEntities())
            {
                //IsDomesticAdmin,IsDomesticCommercial,IsDomesticSales,IsOverseaAdmin,IsOverseaSales
                UserRoles userRole = new UserRoles();
                foreach (var roleid in RoleIDs)
                {
                    if (String.IsNullOrEmpty(roleid))
                        continue;
                    int roleid1 = int.Parse(roleid);
                    var role = dc.Roles.First(p => p.RoleID == roleid1);
                    if (role.BelongsTo == "CID")
                    {
                        userRole.IsDomesticSales = true;
                        userRole.IsDomesticAdmin = userRole.IsDomesticAdmin || role.IsAdmin;
                    }
                    if (role.BelongsTo == "CIO")
                    {
                        userRole.IsOverseaSales = true;
                        userRole.IsOverseaAdmin = userRole.IsOverseaAdmin || role.IsAdmin;
                    }
                }
                return userRole;
            }
        }

        private static bool HasIntersection(IEnumerable<Role> roles1, string[] roles2)
        {
            foreach (var r in roles1)
                if (roles2.Contains(r.RoleID.ToString())) return true;
            return false;
        }

        public static string GetCustomerIDsByCompanyID(int companyID)
        {
            using (var dc = new CCEntities())
            {
                var customers = dc.Customers.Where(p => p.Company.CompanyID == companyID && p.Disabled == false).ToList<Customer>();
                string result = "";
                foreach (var customer in customers)
                {
                    result += customer.CustomerID.ToString();
                    result += ",";
                }
                if (!String.IsNullOrEmpty(result))
                    result = result.Substring(0, result.Length - 1);
                return result;
            }
        }

        /// <summary>
        /// 判断公司所属区域
        /// </summary>
        /// <param name="companyID">公司ID</param>
        /// <returns>true国内，false海外</returns>
        public static bool GetBelongsToByCompanyID(int companyID)
        {
            using (var dc = new CCEntities())
            {
                var company = dc.Companies.First(p => p.CompanyID == companyID);
                company.Countries.Load();
                if (company.Countries.Count <= 0)
                    return true;
                else
                    return false;
            }
        }


        /// <summary>
        /// 获取所有Province
        /// </summary>
        /// <returns></returns>
        public static IEnumerable GetProvince()
        {
            using (var dc = new CCEntities())
            {
                return dc.Provinces.Where(p => p.Disabled == false).ToArray();
            }
        }


        /// <summary>
        /// 获取所有Category
        /// </summary>
        /// <returns></returns>
        public static IEnumerable GetCategory()
        {
            using (var dc = new CCEntities())
            {
                return dc.Categories.Where(p => p.Disabled == false).ToArray();
            }
        }


        /// <summary>
        /// 获取所有Cluster
        /// </summary>
        /// <returns></returns>
        public static IEnumerable GetCluster()
        {
            using (var dc = new CCEntities())
            {
                return dc.Clusters.Where(p => p.Disabled == false).ToArray();
            }
        }

        /// <summary>
        /// 获取Company对应的Province
        /// </summary>
        /// <param name="companyID"></param>
        /// <returns></returns>
        public static int GetProvinceIDByCompanyID(int companyID)
        {
            using (var dc = new CCEntities())
            {
                var company = dc.Companies.First(p => p.CompanyID == companyID);
                company.PCATs.Load();
                if (company.PCATs.Count == 0)
                    return 0;
                return company.PCATs.First().ProvinceID;
            }
        }

        /// <summary>
        /// 获取Company对应的Category
        /// </summary>
        /// <param name="companyID"></param>
        /// <returns></returns>
        public static int GetCateIDByCompanyID(int companyID)
        {
            using (var dc = new CCEntities())
            {
                var company = dc.Companies.First(p => p.CompanyID == companyID);
                company.PCATs.Load();
                if (company.PCATs.Count == 0)
                    return 0;
                return company.PCATs.First().CateID;
            }
        }

        public static IEnumerable GetCountryByRoleID(string[] roles)
        {
            using (var dc = new CCEntities())
            {
                foreach (var role in roles)
                {
                    if (role != "")
                    {
                        var role1 = int.Parse(role);
                        var role2 = dc.Roles.FirstOrDefault(p => p.RoleID == role1 && p.Disabled == false && p.BelongsTo == "CIO");
                        if (role2 != null && role2.IsAdmin == true)
                        {
                            return dc.Countries.Where(p => p.Disabled == false).ToList<Country>().OrderBy(cc => cc.Name);
                        }
                    }
                }
                List<Country> countries = new List<Country>();
                foreach (var role in roles)
                {
                    if (role != "")
                    {
                        var role1 = int.Parse(role);
                        var role2 = dc.Roles.FirstOrDefault(p => p.RoleID == role1 && p.Disabled == false && p.BelongsTo == "CIO");
                        if (role2 != null)
                        {
                            role2.Countries.Load();
                            foreach (var c in role2.Countries)
                            {
                                if (c.Disabled == false)
                                    countries.Add(c);
                            }
                        }
                    }
                }
                return countries.OrderBy(cc => cc.Name);
            }
        }

        public static int GetCountryIDByCompanyID(int companyID)
        {
            using (var dc = new CCEntities())
            {
                var company = dc.Companies.FirstOrDefault(p => p.CompanyID == companyID);
                if (company != null)
                {
                    company.Countries.Load();
                    if (company.Countries.Count > 0)
                        return company.Countries.First(p => p.Disabled == false).CountryID;
                }
                return 0;
            }
        }

        public static string GetAreaByCountryID(int countryID)
        {
            using (var dc = new CCEntities())
            {
                var country = dc.Countries.First(p => p.CountryID == countryID);
                country.Areas.Load();
                var area = country.Areas.FirstOrDefault();
                if (area != null)
                    return area.Name;
                return "";
            }
        }

        /// <summary>
        /// 检查公司名称是否重复
        /// </summary>
        /// <returns></returns>
        public static bool CheckCompanyName(string name, string roles)
        {
            using (var dc = new CCEntities())
            {

                var companies = dc.sp_GetCompanybyRoleID(roles);
                if (companies.Where(p => p.Name == name && p.Disabled == false).Count() > 0)
                    return false;
                return true;
            }
        }

    }

    public class SelectType
    {
        public string id { get; set; }
        public string ischecked { get; set; }
        public string name { get; set; }
    }

    public class UserRoles
    {
        public bool IsDomesticAdmin { get; set; }
        public bool IsDomesticCommercial { get; set; }
        public bool IsDomesticSales { get; set; }

        public bool IsOverseaAdmin { get; set; }
        public bool IsOverseaSales { get; set; }
    }


}
